/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.formmetadata.replication;

import com.fasterxml.jackson.databind.JsonNode;
import com.inspur.edp.lcm.metadata.api.IMetadataContent;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataDto;
import com.inspur.edp.lcm.metadata.common.configuration.MetadataSerializerHelper;
import com.inspur.edp.lcm.metadata.spi.MetadataContentSerializer;
import com.inspur.edp.web.common.customexception.WebCustomException;
import com.inspur.edp.web.common.logger.WebLogger;
import com.inspur.edp.web.common.serialize.SerializeUtility;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.formmetadata.constant.I18nExceptionConstant;
import io.iec.edp.caf.commons.exception.ExceptionLevel;

/**
 * 元数据 content 拷贝
 * 执行的是深拷贝操作，避免引用对象之间的互相更改
 *
 * @author guozhiqi
 */
class MetadataContentCloneManager {
    public static IMetadataContent deepClone(GspMetadata sourceMetadata, MetadataDto metadataDto) {
        IMetadataContent metadataContent = null;
        MetadataContentSerializer transferSerializerManager = MetadataSerializerHelper.getInstance().getManager(sourceMetadata.getHeader().getType());
        if (transferSerializerManager == null) {
            throw new WebCustomException(I18nExceptionConstant.WEB_FORM_METADATA_ERROR_0013, new String[]{sourceMetadata.getHeader().getType()}, ExceptionLevel.Error);
        }

        if (metadataDto != null && StringUtility.isNotNullOrEmpty(metadataDto.getContent())) {
            JsonNode metadataDtoContent = SerializeUtility.getInstance().readTree(metadataDto.getContent());
            metadataContent = transferSerializerManager.DeSerialize(metadataDtoContent);
        } else {
            if (sourceMetadata.getContent() != null) {
                // 执行此操作的目的是为了进行元数据的深拷贝  避免对目标元数据的更改会影响source  metadata
                JsonNode content = transferSerializerManager.Serialize(sourceMetadata.getContent());
                metadataContent = transferSerializerManager.DeSerialize(content);
            }
        }

        return metadataContent;
    }

}
